package com.hotelvip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hotelvip.common.annotation.RequiredLog;
import com.hotelvip.common.exception.ServiceException;
import com.hotelvip.common.pojo.PageObject;
import com.hotelvip.common.utils.ShiroUtils;
import com.hotelvip.dao.SysUserMapper;
import com.hotelvip.dao.SysUserRoleMapper;
import com.hotelvip.entity.SysUser;
import com.hotelvip.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

/**
 * @author Lzh
 * @date 2020/11/30 14:07
 */
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    @RequiredLog(operation = "新增用户")
    @Transactional(noRollbackFor = ServiceException.class)
    public int addUser(SysUser sysUser, Long[] roleIds) {
        //校验
        if (StringUtils.isEmpty(sysUser.getUsername())) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (StringUtils.isEmpty(sysUser.getPassword())) {
            throw new IllegalArgumentException("密码不能为空");
        }
        if (sysUserMapper.findUserByUserName(sysUser.getUsername())!=null) {
            throw new IllegalArgumentException("该用户名已注册");
        }
        //构建盐值对象
        String salt = UUID.randomUUID().toString();
        SimpleHash sh = new SimpleHash("MD5", sysUser.getPassword(), salt, 1);
        String newPassword = sh.toHex();
        //操作人
        String operator = ShiroUtils.getUsername();
        sysUser.setSalt(salt).setPassword(newPassword).setCreatedUser(operator).setUpdatedUser(operator);
        int rows = sysUserMapper.addUser(sysUser);

//        System.out.println(sysUser.getId()+ Arrays.toString(roleIds));
        rows = sysUserRoleMapper.insertRoles(sysUser.getId(), roleIds);

        return rows;
    }
    /**
     * 修改/更新密码
     * @param sourcePassword 原密码
     * @param newPassword 新密码
     * @param cfgPassword 确认密码
     * @return
     */
    @Override
    @RequiredLog(operation = "修改密码")
    @Transactional(noRollbackFor = ServiceException.class)
    public int updateUserPassword(String sourcePassword,String newPassword,String cfgPassword) {
        //1.参数校验
        if(StringUtils.isEmpty(sourcePassword)) {
            throw new IllegalArgumentException("原密码不能为空");
        }
        if(StringUtils.isEmpty(newPassword)) {
            throw new IllegalArgumentException("新密码不能为空");
        }
        if(!newPassword.equals(cfgPassword)) {
            throw new IllegalArgumentException("两次输入的新密码必须一致");
        }
        //验证原密码是否正确.
        SysUser user=ShiroUtils.getUser();
        String salt=user.getSalt();
        SimpleHash sh=new SimpleHash("MD5", sourcePassword, salt, 1);
        if(!user.getPassword().equals(sh.toHex())) {
            throw new IllegalArgumentException("输入的原密码不正确");
        }
        //2.修改密码
        String newSalt=UUID.randomUUID().toString();
        String newHashedPassword=
                new SimpleHash("MD5", newPassword, newSalt, 1).toHex();
        int rows=sysUserMapper.updateUserPassword(user.getUsername(), newHashedPassword, newSalt);
        //3.校验结果并返回
        if(rows==0)
            throw new ServiceException("此用户可能已经不存在");//几率很小
        return rows;
    }

    @Override
    @RequiredLog(operation = "按ID查询用户")
    @Transactional(readOnly = true)//查询
    public SysUser findUserById(Integer id) {
        //校验
        if (StringUtils.isEmpty(id)) {
            throw new IllegalArgumentException("查询的id不能为空");
        }
        //查询
        SysUser sysUser = sysUserMapper.findUserById(id);
        if (sysUser==null) {
            throw new ServiceException("用户可能已经不存在了");
        }
        return sysUser;

    }

    @Override
    @RequiredLog(operation = "修改用户信息")
    @Transactional(noRollbackFor = ServiceException.class)
    public int updateUser(SysUser sysUser) {
        //校验
        if (sysUser.getRoleIds().length==0) {
            throw new IllegalArgumentException("权限不能为空");
        }
        //执行业务 修改用户信息
        int rows = sysUserMapper.updateById(sysUser);
        if (rows == 0) {
            throw new ServiceException("修改数据失败或没有做修改");
        }
        //删除旧的关联数据
        rows = sysUserRoleMapper.deleteObjectsByUserId(sysUser.getId());
        if (rows == 0) {
            throw new ServiceException("修改权限失败或没有做修改");
        }
        rows = sysUserRoleMapper.insertRoles(sysUser.getId(), sysUser.getRoleIds());
        if (rows == 0) {
            throw new ServiceException("更新权限失败或未作更新");
        }
        return rows;
    }
    @Transactional(noRollbackFor = ServiceException.class)
    @RequiredLog(operation = "禁用启用")
    @Override
    public void updateStatus(Integer id, Integer status) {
        //校验参数
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("用户id不在范围内");
        }
            int rows = sysUserMapper.updateStatusById(id, status, ShiroUtils.getUsername());
            if (rows == 0) {
                throw new IllegalArgumentException("用户可能已经不存在");
            }
        }



    /**
     * 查找用户
     * @param pageCurrent 当前页码数
     * @param pageSize  页面大小
     * @return
     */
    @Transactional(readOnly = true)
    @RequiredLog(operation = "查找用户列表信息")
    @Override
    public PageObject<SysUser> findSysUsers(Integer pageCurrent,Integer pageSize) {
        //校验
        if (pageCurrent==null||pageCurrent<1) {
            throw new IllegalArgumentException("页码值不存在");
        }
        if (pageSize==null||pageSize<=1) {
            throw new IllegalArgumentException("每页至少显示一条数据");
        }
        Page<SysUser> page = PageHelper.startPage(pageCurrent, pageSize);
        List<SysUser> sysUsers = sysUserMapper.findSysUsersByUserName();
        //封装返回
        return PageObject.setPageObject(page.getTotal(),sysUsers,Long.valueOf(pageSize),Long.valueOf(pageCurrent));
    }
    @RequiredLog(operation = "登录操作")
    @Override
    public void doLogin(String username) {

    }

    @Override
    @RequiredLog(operation = "注销操作")
    public void doLogout() {

    }

    @Override
    public List<SysUser> selectName(String key) {

        //TODO 目前先使用系统用户代替员工推荐人
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (key != null && key != "") {
            //查询关键字除去前后空格
            String trim = key.trim();
            wrapper.lambda().like(SysUser::getUsername, trim);
        }
        wrapper.lambda().select(SysUser::getUsername, SysUser::getId).eq(SysUser::getStatus, 1);
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(sysUsers)){
            return null;
        }
        return sysUsers;
    }

}
